//
//  GYQuestionViewController.m
//  research
//
//  Created by 章鱼 on 17/3/27.
//  Copyright © 2017年 simon. All rights reserved.
//

#import "GYQuestionViewController.h"
#import "GYQuestionCell.h"
#import "GYNewsListModel.h"
#import "GYInfoViewController.h"
#import "GYLoginViewController.h"
#import "GYUserInfoViewController.h"

@interface GYQuestionViewController ()<
UITableViewDataSource,
UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) NSInteger cpage;//每页显示条数
@property (nonatomic, assign) NSInteger psize;//页数
@property (nonatomic, strong) NSMutableArray *quetionArray;
@property (nonatomic, strong) NSMutableArray *noMoreArray;

@end

@implementation GYQuestionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self basicSetup];
    [self loadNewData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self addRightButtonItemWithTitle:@"" backImg:@"navigation bar_-details_normal"];
}

- (void)rightButtonItemClick {
    [super rightButtonItemClick];
    [self userIsLogin];
}

#pragma mark - action 判断是否登录
- (void)userIsLogin {
    
    [[YGHttpManager defaultManager] fetchGetUserIsloginWithtoken:[[GYConfigDBManager defaultManager] gyToken] success:^(id responseObj) {
        //重新登录
        if ([[responseObj objectForKey:@"status"] integerValue] == 0) {
            if ([[GYConfigDBManager defaultManager] userInformation].userName && [[GYConfigDBManager defaultManager] userInformation].password) {
                
                [[YGHttpManager defaultManager] fetchGetUserLoginWithuserName:[[GYConfigDBManager defaultManager] userInformation].userName password:[[GYConfigDBManager defaultManager] userInformation].password success:^(id responseObj) {
                    GYCommonModel *commonmodel = [GYCommonModel mj_objectWithKeyValues:responseObj];
                    if ([[responseObj objectForKey:@"status"] integerValue] == 0) {
                        [VBAlertView showTextHUD:commonmodel.message];
                        return ;
                    }
                    [[GYConfigDBManager defaultManager] setLogin:YES];
                    [[GYConfigDBManager defaultManager] setGYToken:[commonmodel.data objectForKey:@"token"]];
                    GYUserInfoModel *model = [GYUserInfoModel mj_objectWithKeyValues:[commonmodel.data objectForKey:@"user"]];
                    [[GYConfigDBManager defaultManager] setUserInformation:model];
                    GYUserInfoViewController *userCtrl = [[GYUserInfoViewController alloc] init];
                    userCtrl.hidesBottomBarWhenPushed = YES;
                    userCtrl.tabBarController.tabBar.hidden = YES;
                    [self.navigationController pushViewController:userCtrl animated:YES];
                    
                } failure:^(NSError *error) {
                    
                }];

            }else {
                
                GYLoginViewController *loginCtrl = [[GYLoginViewController alloc] init];
                UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:loginCtrl];
                [self presentViewController:nav animated:YES completion:NULL];
            }
            return ;
        }
        
    } failure:^(NSError *error) {
        
    }];
}

- (void)basicSetup {
    [self initNavBarWithTitle:@"问卷" tintColor:[UIColor orz_mainColor]];
    [self.navBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                         [UIColor whiteColor],NSForegroundColorAttributeName,
                                         [UIFont boldSystemFontOfSize:20],
                                         NSFontAttributeName,
                                         nil]];
    [self.view setBackgroundColor:[UIColor orz_globalBackground]];
}

- (void)startMyCollectQuest {
        
    [[YGHttpManager defaultManager] fetchGetQueslistWithPage:_cpage Pagesize:_psize success:^(id responseObj) {
        GYCommonModel *commonmodel = [GYCommonModel mj_objectWithKeyValues:responseObj];
        GYNewsListModel *model = [GYNewsListModel mj_objectWithKeyValues:commonmodel.data];
        self.noMoreArray = [NSMutableArray arrayWithArray:model.list];
        if (self.noMoreArray.count ==0) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        if (_cpage == 1) {
            [self.quetionArray removeAllObjects];
        }
        [self.quetionArray addObjectsFromArray:model.list];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        
    }];
}


#pragma mark - UI
- (UITableView *)tableView {
    
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.backgroundColor = [UIColor orz_globalBackground];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.showsVerticalScrollIndicator = NO;
        [self.view addSubview:_tableView];
        [self initTableviewUI];
        _tableView.estimatedRowHeight=120.0f;
        _tableView.rowHeight=UITableViewAutomaticDimension;
        [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
        [_tableView registerClass:[GYQuestionCell class] forCellReuseIdentifier:@"GYQuestion"];
        
        MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        header.automaticallyChangeAlpha = YES;
        header.lastUpdatedTimeLabel.hidden = YES;
        _tableView.mj_header = header;
        
        MJRefreshAutoGifFooter *footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        _tableView.mj_footer = footer;
        footer.refreshingTitleHidden = YES;
        [footer setTitle:@"" forState:MJRefreshStateIdle];
        
    }
    return _tableView;
}

#pragma mark - 上拉刷新，下拉加载更多
- (void)loadNewData {
    
    self.cpage = 1;
    self.psize = 4;
    [self startMyCollectQuest];
    [_tableView.mj_header endRefreshing];
    [_tableView.mj_footer endRefreshing];
}
- (void)loadMoreData {
    self.cpage = self.cpage + 1;
    [self startMyCollectQuest];
    [_tableView.mj_header endRefreshing];
    [_tableView.mj_footer endRefreshing];
    
}

- (void)initTableviewUI {
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(64.f);
        make.left.mas_equalTo(0.f);
        make.right.mas_equalTo(0.f);
        make.bottom.mas_equalTo(0.f);
    }];
}

#pragma mark - tableView的代理方法


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _quetionArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    GYQuestionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GYQuestion" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor orz_globalBackground];
    if (_quetionArray.count > indexPath.row) {
        GYQuestInfoModel *model = [GYQuestInfoModel mj_objectWithKeyValues:_quetionArray[indexPath.row]];
        [cell updateCellWithData:model];
    }
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    GYQuestInfoModel *model =[GYQuestInfoModel mj_objectWithKeyValues:_quetionArray[indexPath.row]];
    if (model.status == 1) {
        
        GYInfoViewController *infoCtrl = [[GYInfoViewController alloc] initWithTitle:@"问卷详情" videoType:GYQuestInfoType statuId:model.id];
        infoCtrl.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:infoCtrl animated:YES];
    }else {
        if (model.status == 0) {
            
            [VBAlertView showTextHUD:@"问卷暂未开放"];
        }
        if (model.status == 2) {
            
            [VBAlertView showTextHUD:@"问卷已结束"];
        }
    }
}

- (NSMutableArray *)quetionArray {
    
    if (!_quetionArray) {
        _quetionArray = [NSMutableArray array];
    }
    return _quetionArray;
}
- (NSMutableArray *)noMoreArray {
    
    if (!_noMoreArray) {
        _noMoreArray = [NSMutableArray array];
    }
    return _noMoreArray;
}

@end
